export const int2hex = (decimalNumber) => {
  let hexStr = parseInt(decimalNumber).toString(16) + ''
  console.log('int2hex', decimalNumber, hexStr)
  let len = hexStr.length
  for (let i = 0; i < (6 - len); i ++) {
    hexStr = '0' + hexStr
  }
  return hexStr
}

export const ab2hex = (buffer) => {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function(bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}

export const int2hex2 = (int, len) => {
  if (len) {
    return (int).toString(16).toUpperCase().padStart(len, "0")
  } else {
    return (int).toString(16).toUpperCase()
  }
}


/**
 * 16进制字符串转 ArrayBuffer
 */
export const hexToArrayBuffer = (hex) => {
  let hexArr = hex
  if (typeof hex === 'string') {
    hexArr = hex.match(/[\da-f]{2}/gi)
  }
  return new Uint8Array(
    hexArr.map((byte) => {
      return parseInt(byte, 16);
    })
  ).buffer;
}

 // 防抖函数
  export const debounce = (func, delay) => {
    let timeout;
    return function executedFunction(...args) {
      const later = () => {
        clearTimeout(timeout);
        func(...args);
      };

      clearTimeout(timeout);
      timeout = setTimeout(later, delay);
    };
  };
  
  export function crc8(data, poly = 0x07, init = 0x00, revIn = false, revOut = false, xorOut = 0x00) {
    let crc = init;
  
    for (let i = 0; i < data.length; i++) {
      let byte = data[i];
      if (revIn) {
        byte = reverseByte(byte);
      }
  
      crc ^= byte;
      for (let j = 0; j < 8; j++) {
        if (crc & 0x80) {
          crc = (crc << 1) ^ poly;
        } else {
          crc <<= 1;
        }
      }
      crc &= 0xFF;
    }
  
    if (revOut) {
      crc = reverseByte(crc);
    }
    return (crc ^ xorOut) & 0xFF; 
  }
  
  export function reverseByte(b) {
      let reversed = 0;
      for (let i = 0; i < 8; i++) {
          if (b & 1) {
              reversed |= 1 << (7 - i);
          }
          b >>= 1;
      }
      return reversed;
  }
  
  export function int32ToBytesBigEndian(num) {
    const bytes = [];
    for (let i = 3; i >= 0; i--) {
      bytes.push((num >> (i * 8)) & 0xFF);
    }
    return bytes;
  }
  